<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Light Curve Preview</title>
    <link href="resources/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding: 20px;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .target-container {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
            gap: 15px;
            margin-top: 20px;
        }
        .target-card {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            transition: all 0.3s ease;
            flex-grow: 1;
            min-width: 420px;
            max-width: 420px;
        }
        .target-card:hover {
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .light-curve-img {
            width: 100%;
            height: auto;
            max-width: 400px;
            margin-bottom: 10px;
            cursor: pointer;
        }
        .target-name {
            text-align: center;
            font-weight: bold;
            cursor: pointer;
            color: #0d6efd;
            text-decoration: none;
            word-break: break-all;
        }
        .target-name:hover {
            text-decoration: underline;
        }
        .no-image {
            width: 200px;
            height: 150px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f8f9fa;
            color: #6c757d;
            font-style: italic;
            margin-bottom: 10px;
            cursor: pointer;
        }
        .back-link {
            display: block;
            margin-bottom: 20px;
        }
        .obj-name {
            font-size: 0.9em;
            color: #555;
            margin-top: 5px;
            text-align: center;
            word-break: break-word;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <a href="index.html" class="back-link">← Back to Target List</a>
        
        <div class="header">
            <h1>Light Curve Preview</h1>
            <p>Click on target names or images to view details</p>
        </div>
        
        <div class="target-container" id="targetContainer">
            <!-- Target cards will be loaded here -->
        </div>
    </div>

    <script src="resources/bootstrap.bundle.min.js"></script>
    <script>
        // Define root path
        const rootUrl = '/vtepobjlist';
        
        document.addEventListener('DOMContentLoaded', function() {
            // Fetch all targets
            fetch(`${rootUrl}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(allTargets => {
                    // Process and sort targets by Trig_T0
                    processAndSortTargets(allTargets.objlist);
                    
                    // Display targets
                    displayTargets(allTargets.objlist);
                })
                .catch(error => {
                    console.error('Error fetching targets:', error);
                    document.getElementById('targetContainer').innerHTML = 
                        '<div class="col-12 text-center text-danger">Error loading target data</div>';
                });
                
            function processAndSortTargets(allTargets) {
                // Process Trig_T0 for each target
                allTargets.forEach(obj => {
                    const raw = obj.Trig_T0;

                    if (typeof raw === 'string') {
                        // Remove trailing UTC and possible quotes
                        let cleaned = raw.replace(/UTC"?$/, '');

                        // Remove decimal seconds
                        cleaned = cleaned.replace(/\.\d+/, '');
                        cleaned = cleaned.replace(" ", '');

                        // Try to parse as Date
                        const parsedDate = new Date(cleaned);

                        // Check if valid time
                        if (!isNaN(parsedDate.getTime())) {
                            obj._formatted_T0 = parsedDate;
                        } else {
                            obj._formatted_T0 = null;  // Mark as invalid time
                        }
                    } else {
                        obj._formatted_T0 = null;
                    }
                });
                
                // Sort targets
                allTargets.sort((a, b) => {
                    const timeA = a._formatted_T0;
                    const timeB = b._formatted_T0;

                    let tflag = 0; // Both invalid, keep order
                    if (timeA && timeB) tflag = timeB - timeA;     // Normal time comparison (newest first)
                    if (timeA && !timeB) tflag = -1;               // A has time, put first
                    if (!timeA && timeB) tflag = 1;                // B has time, put first
                    return tflag;                                     
                });
            }
            
            function displayTargets(allTargets) {
                const targetContainer = document.getElementById('targetContainer');
                targetContainer.innerHTML = '';
                
                allTargets.forEach(target => {
                    const card = document.createElement('div');
                    card.className = 'target-card';
                    
                    // Get the first observation type (for the link)
                    const firstType = target.obslist && target.obslist.length > 0 ? 
                        target.obslist[0].type : '';
                    
                    // Create the detail page URL
                    const detailUrl = `detail.html?name=${encodeURIComponent(target.obj_name)}&type=${encodeURIComponent(firstType)}&dataType=quicklook`;
                    
                    // Get quickLook light curve image
                    const qlImage = target.obslist && target.obslist.length > 0 && 
                        target.obslist[0].quickLook && 
                        target.obslist[0].quickLook.lightCurveImage ?
                        `${rootUrl}/files/${target.obslist[0].quickLook.lightCurveImage}` : null;
                    
                    // Create image element (clickable)
                    if (qlImage && !qlImage.includes('null')) {
                        const img = document.createElement('img');
                        img.src = qlImage;
                        img.alt = `${target.name} Light Curve`;
                        img.className = 'light-curve-img';
                        img.addEventListener('click', () => {
                            window.location.href = detailUrl;
                        });
                        card.appendChild(img);
                    } else {
                        const noImg = document.createElement('div');
                        noImg.className = 'no-image';
                        noImg.textContent = 'No image available';
                        noImg.addEventListener('click', () => {
                            window.location.href = detailUrl;
                        });
                        card.appendChild(noImg);
                    }
                    
                    // Create target name link
                    const nameLink = document.createElement('a');
                    nameLink.textContent = target.name;
                    nameLink.className = 'target-name';
                    nameLink.href = detailUrl;
                    card.appendChild(nameLink);
                    
                    // Add obj_name below the image (clickable)
                    if (target.obj_name) {
                        const objName = document.createElement('div');
                        objName.className = 'obj-name';
                        objName.textContent = target.obj_name;
                        objName.addEventListener('click', () => {
                            window.location.href = detailUrl;
                        });
                        card.appendChild(objName);
                    }
                    
                    targetContainer.appendChild(card);
                });
            }
        });
    </script>
</body>
</html>